package com.sailfish.springbootdemo.service.db1;

import com.alibaba.fastjson.JSONObject;
import com.sailfish.springbootdemo.common.DB1EmailTemplates;
import com.sailfish.springbootdemo.common.StrToCompanys;
import com.sailfish.springbootdemo.configs.UserHeaderHolder;
import com.sailfish.springbootdemo.dao.db1.*;
import com.sailfish.springbootdemo.dao.db4.UserDao;
import com.sailfish.springbootdemo.pojo.Result;
import com.sailfish.springbootdemo.pojo.db1.*;
import com.sailfish.springbootdemo.pojo.db2.MailAddress;
import com.sailfish.springbootdemo.pojo.db4.Operate;
import com.sailfish.springbootdemo.pojo.db4.User;
import com.sailfish.springbootdemo.service.db2.ThirdApiService;
import com.sailfish.springbootdemo.service.db4.OperateService;
import com.sailfish.springbootdemo.utils.CommonUtils;
import com.sailfish.springbootdemo.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class PcbaFileServiceImpl implements PcbaFileService {

    @Autowired
    private PcbaFileDao pcbaFileDao;

    @Autowired
    private FileGroupDao fileGroupDao;

    @Autowired
    private BrandDao brandDao;

    @Autowired
    private BrandTypeDao brandTypeDao;

    @Autowired
    private PcbaDeviceTypeDao pcbaDeviceTypeDao;

    @Autowired
    private PcbaDeviceResourceDao pcbaDeviceResourceDao;

    @Autowired
    private AuditHistoryDao auditHistoryDao;

    @Autowired
    private PcbaCompanyDao pcbaCompanyDao;

    @Value("${personal.config.env}")
    private String env;

    @Autowired
    private ThirdApiService thirdApiService;

    @Autowired
    private UserDao userDao;

    @Autowired
    private OperateService operateService;

    private String operateSmallType = "设备档案库";

    @Autowired
    private StrToCompanys strToCompanys;

    @Override
    public List<String> getPcbaFileGroupByResourceId(Integer pcbaDeviceResourceId) {
        return pcbaFileDao.getPcbaFileGroupByResourceId(pcbaDeviceResourceId);
    }

    @Override
    public List<PcbaFile> getAllPcbaFileByStatus(Integer status, Integer pcbaCompanyId, String searchFileName) {
        List<Integer> companyIdList = strToCompanys.getPcbaCompanyIdListFromStr();
        List<PcbaFile> list = pcbaFileDao.getAllPcbaFileByStatus(status, pcbaCompanyId, searchFileName, companyIdList);
        for (PcbaFile pcbaFile : list) {
            pcbaFile.setFileGroup(fileGroupDao.getFileGroupById(pcbaFile.getFileGroupId()));
            pcbaFile.setPcbaCompany(pcbaCompanyDao.getPcbaCompanyById(pcbaFile.getPcbaCompanyId()));
            if (pcbaFile.getPcbaDeviceResourceId() != null && !"".equals(pcbaFile.getPcbaDeviceResourceId().toString())) {
                PcbaDeviceResource pcbaDeviceResource = pcbaDeviceResourceDao.getById(pcbaFile.getPcbaDeviceResourceId());
                if(pcbaDeviceResource != null){
                    Brand brandById = brandDao.getBrandById(pcbaDeviceResource.getBrandId());
                    if(brandById != null){
                        pcbaDeviceResource.setBrand(brandById);
                    }
                    BrandType brandTypeById = brandTypeDao.getBrandTypeById(pcbaDeviceResource.getBrandTypeId());
                    if(brandTypeById != null){
                        pcbaDeviceResource.setBrandType(brandTypeById);
                    }
                    PcbaDeviceType byId = pcbaDeviceTypeDao.getById(pcbaDeviceResource.getPcbaDeviceTypeId());
                    if(byId != null){
                        pcbaDeviceResource.setPcbaDeviceType(byId);
                    }
                    pcbaFile.setPcbaDeviceResource(pcbaDeviceResource);
                }
            }
            User creator = userDao.getUserInfoById(pcbaFile.getCreatorId());
            if (creator != null) {
                pcbaFile.setCreator(creator);
            }
        }
        return list;
    }

    @Override
    public Result addPcbaFile(PcbaFile pcbaFile) {
        try {
            String pcbaFilePath = pcbaFile.getPcbaFilePath();
            if (pcbaFilePath == null || "".equals(pcbaFilePath)) {
                return ResultUtil.error(500, "缺少参数pcbaFilePath", "Miss Param pcbaFilePath", null);
            }

            String userId = UserHeaderHolder.getUserId();

            String pcbaFileName = pcbaFilePath.substring(pcbaFilePath.lastIndexOf("\\") + 1);
            String extendName = pcbaFileName.substring(pcbaFileName.lastIndexOf(".") + 1);
            /*1：图片
            2：excel
            3：pdf
            4：ppt
            5：word
            10：其他未知*/
            /*Integer pcbaFileType = 10;
            if (extendName.toUpperCase().equals("PNG") || extendName.toUpperCase().equals("JPG") || extendName.toUpperCase().equals("JPEG")) {
                pcbaFileType = 1;
            } else if (extendName.toUpperCase().equals("XLSX") || extendName.toUpperCase().equals("XLS")) {
                pcbaFileType = 2;
            } else if (extendName.toUpperCase().equals("PDF")) {
                pcbaFileType = 3;
            } else if (extendName.toUpperCase().equals("PPT") || extendName.toUpperCase().equals("PPTX")) {
                pcbaFileType = 4;
            } else if (extendName.toUpperCase().equals("DOC") || extendName.toUpperCase().equals("DOCX")) {
                pcbaFileType = 5;
            }*/

            Date d = new Date();

            pcbaFile.setPcbaFileName(pcbaFileName);
            //pcbaFile.setPcbaFileType(pcbaFileType);
            pcbaFile.setCreateTime(new Date());
            pcbaFile.setSubmitter(Integer.parseInt(userId));
            pcbaFile.setCreatorId(Integer.parseInt(userId));
            Integer integer = pcbaFileDao.addPcbaFile(pcbaFile);
            if (integer > 0) {

                // 操作日志
                operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 1, 1, d, null, JSONObject.toJSONString(pcbaFile)));

//                // 添加 审核记录
//                AuditHistory addAuditHistory = new AuditHistory();
//                addAuditHistory.setAuditType(6);
//                addAuditHistory.setCreateTime(d);
//                addAuditHistory.setSubmitUserId(Integer.parseInt(userId));
//                addAuditHistory.setAuditUserId(null);
//                addAuditHistory.setAuditStatus(pcbaFile.getStatus());
//                addAuditHistory.setAuditNotes(null);
//                addAuditHistory.setRelatedId(pcbaFile.getPcbaFileId());
//                auditHistoryDao.addAuditHistory(addAuditHistory);
                return ResultUtil.success(null);
            }
            return ResultUtil.error(500, "操作失败", "Operate Fail", null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Override
    public Result deletePcbaFile(Integer pcbaFileId) {
        try {
            if (pcbaFileId == null || "".equals(pcbaFileId.toString())) {
                return ResultUtil.error(500, "缺少参数pcbaFileId", "Miss Param pcbaFileId", null);
            }

            String userId = UserHeaderHolder.getUserId();
            PcbaFile oldPcbaFile = pcbaFileDao.getPcbaFileById(pcbaFileId);

            Integer integer = pcbaFileDao.deletePcbaFile(pcbaFileId);

            if (integer > 0) {

                // 操作日志
                operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 2, 1, new Date(), JSONObject.toJSONString(oldPcbaFile), null));

                return ResultUtil.success(null);
            }
            return ResultUtil.error(500, "操作失败", "Operate Fail", null);

        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Override
    public Result updatePcbaFileStatus(Integer status, String notes, Integer pcbaFileId) {
        try {
            if (pcbaFileId == null || "".equals(pcbaFileId.toString())) {
                return ResultUtil.error(500, "缺少参数pcbaFileId", "Miss Param pcbaFileId", null);
            }

            String userId = UserHeaderHolder.getUserId();
            Date d = new Date();
            PcbaFile oldPcbaFile = pcbaFileDao.getPcbaFileById(pcbaFileId);

            if (status == 1) {
                notes = "";
            }
            Integer integer = pcbaFileDao.updatePcbaFileStatus(status, notes, pcbaFileId, Integer.parseInt(userId));

            if (integer > 0) {

                PcbaFile newPcbaFile = pcbaFileDao.getPcbaFileById(pcbaFileId);
                // 操作日志
                operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 3, 1, d, JSONObject.toJSONString(oldPcbaFile), JSONObject.toJSONString(newPcbaFile)));

                // 添加 审核记录
                AuditHistory addAuditHistory = new AuditHistory();
                addAuditHistory.setAuditType(6);
                addAuditHistory.setCreateTime(d);
                addAuditHistory.setSubmitUserId(null);
                addAuditHistory.setAuditUserId(Integer.parseInt(userId));
                addAuditHistory.setAuditStatus(status);
                addAuditHistory.setAuditNotes(notes);
                addAuditHistory.setRelatedId(pcbaFileId);
                auditHistoryDao.addAuditHistory(addAuditHistory);

                // 发送邮件通知
                try {
                    List<User> userList = new ArrayList<>();
                    Integer pcbaCompanyId = oldPcbaFile.getPcbaCompanyId();
                    if (pcbaCompanyId != null) {
                        PcbaCompany pcbaCompany = pcbaCompanyDao.getPcbaCompanyById(pcbaCompanyId);
                        if (pcbaCompany != null) {
                            String emailOwners5 = pcbaCompany.getEmailOwners5();
                            if (emailOwners5 != null && !"".equals(emailOwners5)) {
                                String[] split = emailOwners5.split(",");
                                for (String s : split) {
                                    if (s.contains("/")) {
                                        String[] strings = s.split("\\/");
                                        if (strings.length == 2) {
                                            String domainAccount = strings[1];
                                            if (domainAccount != null && !"".equals(domainAccount)) {
                                                User u = userDao.getUserInfoByDomainAccount(domainAccount);
                                                if (u != null) {
                                                    userList.add(u);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    List<MailAddress> mailAddressList = new ArrayList<>();
                    for (User user : userList) {
                        if(user.getEmail().contains(",")){
                            String[] emailsArr = user.getEmail().split(",");
                            for (String email : emailsArr) {
                                MailAddress mailAddress = new MailAddress();
                                mailAddress.setMailAddress(email);
                                mailAddress.setType(0);
                                mailAddressList.add(mailAddress);
                            }
                        }else{
                            MailAddress mailAddress = new MailAddress();
                            mailAddress.setMailAddress(user.getEmail());
                            mailAddress.setType(0);
                            mailAddressList.add(mailAddress);
                        }
                    }
                    if (mailAddressList.size() > 0) {
                        if (status == 1) {
                            Result result = thirdApiService.sendMail("", DB1EmailTemplates.LIBRARY_TITLE_OK, DB1EmailTemplates.LIBRARY_MAIL_CONTENT_TITLE_OK,
                                    DB1EmailTemplates.LIBRARY_MAIL_CONTENT_OK, "10086", mailAddressList, null, null, null, null, 2, null);
                            if (result.getCode() == 200) {
                                System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                                System.out.println("档案库审核结果邮件,发送成功");
                            } else {
                                System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                                System.out.println("档案库审核结果邮件,发送失败:" + result.getMsgCn());
                            }
                        } else if (status == 2) {
                            Result result = thirdApiService.sendMail("", DB1EmailTemplates.LIBRARY_TITLE_NO, DB1EmailTemplates.LIBRARY_MAIL_CONTENT_TITLE_NO,
                                    DB1EmailTemplates.LIBRARY_MAIL_CONTENT_NO, "10086", mailAddressList, null, null, null, null, 2, null);
                            if (result.getCode() == 200) {
                                System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                                System.out.println("档案库审核结果邮件,发送成功");
                            } else {
                                System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                                System.out.println("档案库审核结果邮件,发送失败:" + result.getMsgCn());
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println(CommonUtils.formatCurrentTime() + "==========================================");
                    System.out.println("档案库审核结果邮件发送失败");
                }


                return ResultUtil.success(null);
            }
            return ResultUtil.error(500, "操作失败", "Operate Fail", null);

        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Override
    public Result updatePcbaFile(PcbaFile pcbaFile) {
        try {
            if (pcbaFile == null) {
                return ResultUtil.error(500, "缺少参数pcbaFile", "Miss Param pcbaFile", null);
            }
            if (pcbaFile.getPcbaFileId() == null || "".equals(pcbaFile.getPcbaFileId().toString())) {
                return ResultUtil.error(500, "缺少参数pcbaFileId", "Miss Param pcbaFileId", null);
            }

            String userId = UserHeaderHolder.getUserId();
            PcbaFile oldPcbaFile = pcbaFileDao.getPcbaFileById(pcbaFile.getPcbaFileId());

            pcbaFile.setCreatorId(Integer.parseInt(userId));
            Integer integer = pcbaFileDao.updatePcbaFile(pcbaFile);

            if (integer > 0) {

                // 操作日志
                operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 3, 1, new Date(), JSONObject.toJSONString(oldPcbaFile), JSONObject.toJSONString(pcbaFile)));

                return ResultUtil.success(null);
            }
            return ResultUtil.error(500, "操作失败", "Operate Fail", null);

        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Override
    public Result updatePcbaFileRelatedPcbaDeviceResource(Integer pcbaDeviceResourceId, Integer fileGroupId, Integer pcbaFileId) {
        try {
            if (pcbaFileId == null || "".equals(pcbaFileId.toString())) {
                return ResultUtil.error(500, "缺少参数pcbaFileId", "Miss Param pcbaFileId", null);
            }
            if (fileGroupId == null || "".equals(fileGroupId.toString())) {
                return ResultUtil.error(500, "缺少参数fileGroupId", "Miss Param fileGroupId", null);
            }

            String userId = UserHeaderHolder.getUserId();
            PcbaFile oldPcbaFile = pcbaFileDao.getPcbaFileById(pcbaFileId);

            Integer integer = pcbaFileDao.updatePcbaFileRelatedPcbaDeviceResource(pcbaDeviceResourceId, fileGroupId, pcbaFileId);

            if (integer > 0) {

                PcbaFile newPcbaFile = pcbaFileDao.getPcbaFileById(pcbaFileId);
                // 操作日志
                operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 3, 1, new Date(), JSONObject.toJSONString(oldPcbaFile), JSONObject.toJSONString(newPcbaFile)));

                return ResultUtil.success(null);
            }
            return ResultUtil.error(500, "操作失败", "Operate Fail", null);

        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }
}
